1. Background

$$\newcommand{\kon}{k_{\mathrm{on}}} \newcommand{\koff}{k_{\mathrm{off}}} \newcommand{\kcat}{k_{\mathrm{cat}}} \newcommand{\kuncat}{k_{\mathrm{uncat}}} \newcommand{\kms}{k_{m,\mathrm{S}}} \newcommand{\kmp}{k_{m,\mathrm{P}}} \newcommand{\dSdt}{\frac{d[\mathrm{S}]}{dt}} \newcommand{\dEdt}{\frac{d[\mathrm{E}]}{dt}} \newcommand{\dESdt}{\frac{d[\mathrm{ES}]}{dt}} \newcommand{\dPdt}{\frac{d[\mathrm{P}]}{dt}}$$

1.1 Enzyme Kinetics

Enzymes catalyze many critical chemical reactions in cells.

Describing a cell with a mathematical model (a long-standing goal of computational biologists) would entail modelling each enzyme-catalyzed chemical reaction.

However, although we may know the scheme for many enzymatic reactions (the responsible enzyme, the associated substrates, and resultant products) we are often missing many of the details needed to construct a faithful mathematical model of the reaction.

Let's begin by introducing the mathematical model used to describe enzymatic reaction schemes. Consider the following enzymatically-catalyzed (uni uni) chemical reaction scheme:

$$ E+S \underset{\koff}{\overset{\kon}{\rightleftarrows}} ES \underset{\kuncat}{\overset{\kcat}{\rightleftarrows}}E+P $$

In this scheme E is an enzyme, S is its substrate, ES is the enzyme-substrate complex, which is an intermediate, and P is the product of the reaction. Each of those chemical species has a concentration in a fixed volume, which we denote with brackets (e.g. $[\mathrm{E}]$ = enzyme concentration).

If we make the simplifying assumption that the 4 molecular species are 'well-mixed' in solution, we can invoke the 'Law of Mass Action' under which the rate of each of the four included reactions is linear in the concentrations of the reactants (with an associated coefficient called the rate constant). The reactions in the above scheme are: enzyme-substrate association ($\kon$), dissociation ($\koff$), enzyme catalysis of substrate into product ($\kcat$), and enzyme-product re-association ("uncatalysis", $\kuncat$). The designation of 'substrate' and 'product' is our choice -- the model is entirely symmetric, which is reflected in the associated ODEs:

$$\begin{aligned} \frac{d[\mathrm{S}]}{dt} &= k_{\mathrm{off}}[\mathrm{ES}] - k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] \\ \frac{d[\mathrm{E}]}{dt} &= k_{\mathrm{off}}[\mathrm{ES}] - k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] + k_{\mathrm{cat}}[\mathrm{ES}] - k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ \frac{d[\mathrm{ES}]}{dt} &= - k_{\mathrm{off}}[\mathrm{ES}] + k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] - k_{\mathrm{cat}}[\mathrm{ES}] + k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ \frac{d[\mathrm{P}]}{dt} &= k_{\mathrm{cat}}[\mathrm{ES}] - k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \end{aligned}$$

This differential equation model describing the (deterministic) chemical kinetics for an enzymatically-catalyzed reaction in well-mixed conditions contains 4 kinetic parameters, i.e. 4 degrees of freedom, which we do not know a priori. These will be the subject of inference.

Note: the intracellular environment is not best described as well-mixed, and models of ’Macromolecular Crowding’ have led to more accurate rate laws for these reactions in vivo. However, we will retain the well-mixed assumption for now.

1.2 Parameter Inference

There are 3 typical problems associated with ODE models:

  • Supplied with a complete specification of the system, the forward problem is to integrate the differential equations from some initial conditions forwards in time and predict the trajectory of the system. This is what is typically meant by "solving" the ODE system, but exact analytical solutions are rare, and numerical methods are often brought to bear to approximate system trajectories.
  • Supplied with one or more trajectories (data) but incomplete specification of the system, the inverse problem is to estimate parameters of the system (coefficients in the ODE expressions).
  • Finally, given some manipulable inputs, the control problem is to drive the system towards some desired state.

This post will explore a range of approaches for the inverse problem. Our goal will be to estimate the kinetic parameters of enzymatically-catalyzed chemical reactions from timeseries of concentrations of the molecular species.

Note: enzyme kinetic parameters are typically not inferred from metabolite timeseries data using the methods we will describe, but instead from specific enzyme assays. However, at the moment, these assays are limited to studying one enzyme at a time. The inference approaches described in this post can leverage data from emerging high-throughput assays.

The determination of the kinetic parameters for the enzymatic reactions of life is a major project, and reported values have been tabulated in databases such as BRENDA. However, my experience with these databases has been that the reported kinetic parameters are not internally consistent.

1.3 The Michaelis-Menten/Briggs-Haldane Approximation

Two assumptions commonly made at this point are:

  1. to assume the initial substrate concentration is much larger than the enzyme concentration ($[\mathrm{S_0}] \gg [\mathrm{E_0}]$).
  2. to suppose that the rates of enzyme-substrate association ($\kon$) and dissociation ($\koff$) are greater than the rates of catalysis and uncatalysis (i.e. $\kon$, $\koff$ $\gg$ $\kcat$, $\kuncat$).

These assumptions permit a timescale separation argument called the "Quasi-Steady-State Approximation" (QSSA) in which we set $\dESdt = 0$, which enables the derivation of the traditional Reversible Michaelis-Menten/Briggs-Haldane expression:

$$\begin{aligned} \frac{d[\mathrm{P}]}{dt} &= \frac{ \frac{\kcat \, [\mathrm{E_T}] [\mathrm{S}]}{K_{m,\mathrm{S}}} - \frac{\koff \, [\mathrm{E_T}] [\mathrm{P}]}{K_{m,\mathrm{P}}}} {1+\frac{[\mathrm{S}]}{K_{m,\mathrm{S}}} + \frac{[\mathrm{P}]}{K_{m,\mathrm{P}}}} \\ \\ \frac{d[\mathrm{S}]}{dt} &= -\frac{d[\mathrm{P}]}{dt} \end{aligned}$$

in which we have introduced the "Michaelis Constants": $K_{m,\mathrm{S}} = \frac{\koff + \kcat}{\kon}$ and $K_{m,\mathrm{P}} = \frac{\koff + \kcat}{\kuncat}$.

The QSSA reduces the system from 4 variables to 2. However, there are still 4 kinetic parameters to estimate in this reduced model.

Note: another assumption typically made at this point is to assume that catalysis is irreversible ($\kuncat = 0$), leading to a further simplified expression for the rate of product formation $\frac{d[\mathrm{P}]}{dt}$. However, this assumption is quite often inaccurate, so we will not make it.

2. Exploring the Forward Model

2.1 A Standard Example

Before we explore techniques to estimate enzyme kinetic parameters from timeseries data, we need to generate timeseries data to begin with. We can accomplish that by fixing kinetic parameters, then solving the forward problem. It will turn out that integrating the differential equations forwards is a subroutine of both approaches to the inverse problem we'll see in this post, so developing a method for the forward problem is hardly wasted effort.

In order to produce a trajectory, we need to set initial conditions. We'll integrate the reaction kinetics of a hypothetical in vitro experiment, in which a fixed quantity of enzyme and substrate are added to the reaction at the outset, then left to react.

Note: in vivo we would expect the concetration of enzyme to vary over time, and the substrate to be replenished. We will generalize this approach to a more biologically-relevant setting in a future post.

Our initial conditions are:

  • $[E]_0$, the initial enzyme concentration, is set to 1mM (miliMolar, i.e. 1000μM).
  • $[S]_0$, the initial substrate concentration is set to 10mM.
default_initial_conditions = {
    'S_0': 10e3,
    'E_0': 1e3,
    'ES_0': 0.0,
    'P_0': 0.0
}

Next, let's fix some generic rate constants:

  • $\kon \,$ of $10^6$ events per Mol per second, or 1 per μM per second, is a typical rate for enzyme-substrate binding.
  • $\koff \,$ of 500/s results in a $\koff$/$\kon$ = $k_d$ of 500 μM, which is a typical $k_d$.
  • $\kcat \,$ is 30/s, a fairly slow but respectable $\kcat$.
  • $\kuncat \,$ of $\frac{\kon}{10}$ is often considered as the boundary for the QSSA to hold (so 0.1 per μM per second). Let's use $\kuncat = \frac{\kon}{100} = $ 0.01/μM for good measure.

Our units are μM and seconds.

default_kinetic_params = {
    'k_on': 1,
    'k_off': 500,
    'k_cat': 30,
    'k_uncat': 0.01
}

def k_ms(p): return (p['k_off'] + p['k_cat']) / p['k_on']
def k_mp(p): return (p['k_off'] + p['k_cat']) / p['k_uncat']

default_kinetic_params['k_ms'] = k_ms(default_kinetic_params)
default_kinetic_params['k_mp'] = k_mp(default_kinetic_params)

To simulate the kinetics with little derivative steps, we need a step size, and a number of total steps:

dt = 1e-6
steps = 5e5

There are a variety of numerical methods to integrate systems of differential equations. The most straightforward is Euler's method, which we've written down explicitly for this system below:

We'll also write down Euler's method for the Michaelis-Menten/Briggs-Haldane kinetics

Now we can integrate the reaction kinetics, and plot the trajectory. We'll overlay the Michaelis-Menten/Briggs-Haldane kinetics with dotted lines on top of the full kinetics (solid).

traj_euler_full = integrate_euler_full(default_kinetic_params)
traj_euler_mm = integrate_euler_MM(default_kinetic_params)
ax = traj_euler_full.plot.line(title=param_string(**default_initial_conditions, **default_kinetic_params), color=color(traj_euler_full.columns))
traj_euler_mm.plot.line(ax=ax, color=color(traj_euler_mm.columns), linestyle='--')

fig_style(ax)

We can plainly see the validity of the Quasi-Steady-State Approximation (QSSA) in action in the trajectory: Enzyme E and Substrate S rapidly form Enzyme-Substrate complex ES, the concentration of which remains relatively constant throughout the course of the reaction (recall the QSSA is the approximation that $\dESdt = 0$). Thus, the Michaelis-Menten/Briggs-Haldane product concentration trajectory P_MM well approximates the full kinetics trajectory for the concentration of product P, since the requisite assumptions are valid, namely, (1) $[\mathrm{S_0}] \gg [\mathrm{E_0}]$ and (2) $\kon$, $\koff$ $\gg$ $\kcat$, $\kuncat$.

In practice, Michaelis-Menten/Briggs-Haldane kinetics are often assumed by default, risking the possibility of their misapplication. Let's take this opportunity to explore how the MM/BH kinetics diverge from the full kinetics when we violate the requisite assumptions.

2.2: Breaking the Michaelis-Menten/Briggs-Haldane Assumptions:
      Initial Substrate:Enzyme Ratio

Suppose first the number of molecules of substrate is not much greater than the number of molecules of enzyme, which is a plausible regime for certain reactions in vivo.

initial_conditions = {
    'S_0': 2e3,
    'E_0': 1e3,
    'ES_0': 0.0,
    'P_0': 0.0
}

Then P_MM worsens significantly as an estimate of P.

2.3: Breaking the Michaelis-Menten/Briggs-Haldane Assumptions:
      Fast Enzyme-Substrate Complex Kinetics

Suppose further that the rates of association and dissociation of enzyme with subtstrate are not substantially faster than those of enzyme and product.

kinetic_params = {
    'k_on': 0.05,
    'k_off': 1,
    'k_cat': 50,
    'k_uncat': 0.5
}

kinetic_params['k_ms'] = k_ms(kinetic_params)
kinetic_params['k_mp'] = k_mp(kinetic_params)

Then the Michaelis-Menten/Briggs-Haldane kinetics diverge further.

In each of these latter trajectories, the criteria to make the Michaelis-Menten/Briggs-Haldane approximation are violated, leading to poor approximations to the full kinetics. We belabor this point here because in the following, we will seek to infer the parameters of the kinetics, and our inference will fit poorly if we fit to inappropriate kinetic expressions.

2.4: Comparing Integrators

All of the above trajectories are generated by Euler's Method, the most intuitive ODE integration technique. Unfortunately, Euler's Method's naïvete has drawbacks:

  • The order of the error is large with respect to the timestep size.
  • The method is slow, due to the uniformity of the timestep sizes.

A variety of faster and more accurate (albeit more complicated) integrators have been proposed, many of which have implementations in scipy's integrate package. Due to their superior speeds and accuracies, we'll use these methods during inference. As a sanity check, we compare our basic Euler Method solver to scipy's:

The lack of deviation gives us confidence both integration techniques are accurate. Meanwhile,

f'our naïve code takes {round(euler_time, 2)}s, whereas the optimized scipy code takes {round(scipy_time, 4)}s to generate the same trajectory.'
'our naïve code takes 1.11s, whereas the optimized scipy code takes 0.0103s to generate the same trajectory.'

3. Inference

We have seen how the trajectory of the chemical system is a function of the kinetic parameters. We would now like to invert that function to recover the kinetic parameters from an observed trajectory.

Suppose we know the initial concentrations of Enzyme E and Substrate S, and we measure the concentration of product P over the course of the reaction, which yields the following dataset:

We will supply noiseless measurements to our inference algorithms. However, our inference procedures will assume noise in the measurements.

Note: If we had measured $\dPdt$ for various (linearly independent) concentrations of $[\mathrm{S}]$, $[\mathrm{P}]$, and $[\mathrm{E}]_0$ (as in an in vitro enzyme assay) we could use a nonlinear regression with the Michaelis-Menten/Briggs-Haldane expression for $\dPdt$. Concretely, supposing we had a set of measurements for the variables in blue, a nonlinear regression would permit us to fit the constants in red: $$\color{blue}{\dPdt} = \frac{ \frac{\color{red}{\kcat} \, \color{blue}{[\mathrm{E_T}]} \color{blue}{[\mathrm{S}]}} {\color{red}{K_{m,\mathrm{S}}}} - \frac{\color{red}{\koff} \, \color{blue}{[\mathrm{E_T}]} \color{blue}{[\mathrm{P}]}}{\color{red}{K_{m,\mathrm{P}}}}} {1+\frac{\color{blue}{[\mathrm{S}]}}{\color{red}{K_{m,\mathrm{S}}}} + \frac{\color{blue}{[\mathrm{P}]}}{\color{red}{K_{m,\mathrm{P}}}}} $$ If we had assumed the reaction were irreversible, the Michaelis-Menten/Briggs-Haldane expression would have simplified to $$\color{blue}{\dPdt} = \frac{ \color{red}{\kcat} \, \color{blue}{[\mathrm{E_T}]} \color{blue}{[\mathrm{S}]}} {\color{red}{K_{m,\mathrm{S}}} + \color{blue}{[\mathrm{S}]}} $$ Where $\color{red}{\kcat} \, \color{blue}{[\mathrm{E_T}]}$ is often consolidated as $\color{red}{V_{max}}$. To recap, we take a different approach because:
  1. Simultaneous measurements of the activity many enzymes in cells might inform us about $[\mathrm{S}]$, $[\mathrm{P}]$, and perhaps $[\mathrm{E}]$ but not $\dPdt$. We would also presumably not be able to approximate $\dPdt$ via finite differences, due to the relative sparsity of the measurement in time compared to the rates of the reactions.
  2. This approach would produce spurious estimates of the kinetic parameters in cases in which the Quasi-Steady-State Approximation is invalid (see §2.2, §2.3) which may often be the case in vivo.
At the moment, I believe there are no methods for the inverse problem which are not variants of the two methods I will describe, and importantly, no methods which do not iterate a loop, solving the forward problem at each iteration.

There are two types of approaches to solving this inverse problem. We will explore the simplest variant of each type.

3.1 Bayesian Approach: Inference by Sampling

[We assume the reader is familiar with Bayesian Inference in other settings.]

The goal of the Bayesian approach is to characterize a distribution of kinetic parameters which could plausibly have generated the data, called the posterior distribution. Bayes Theorem defines the posterior as the product of the prior and likelihood (up to a constant factor). Thus the Bayesian approach entails defining a prior and a likelihood for our problem.

3.1.1. Prior

If the kinetic parameters of our enzyme are not unlike the kinetic parameters of other enzymes, then the empirical distribution of kinetic parameters of other enzymes is a good prior for the parameters of our enzyme.

Since databases of observed enzyme kinetic parameters (e.g. BRENDA, SabioRK) appear to be unreliable, we'll use a previously curated set of kinetic parameters (from the supplement of Bar-Even et. al.).

This database lists $k_{\mathrm{m}}$ and $\kcat$ for both "forwards" and "reverse" reactions with respect to which direction biologists believe is "productive", from which we can parlay distributions for $\kms$ and $\kcat$ from reactions in the forwards direction, and $\kmp$ and $\koff$ from reverse reactions.

This plot is surprising: according to this database, enzymes appear to have roughly equal binding affinity for their substrates and products.

On the other hand, they have a fairly strong preference for catalyzing the reaction biologists think of as forwards (~10x).

Since these empirical distributions over $\kms$ and $\kcat$ in the forwards direction and $\kmp$ and $\koff$ in the reverse direction look sufficiently like normals in log space, so we'll treat them as lognormals. However, we would like our inference procedure to estimate the semantic parameters $\kon$, $\koff$, $\kcat$, and $\kuncat$. We can rearrange the expressions for $\kms$ and $\kmp$ to get expressions for the two parameters we're missing:

$$ \kon = \frac{\koff + \kcat}{\kms} \quad \mathrm{and} \quad \kuncat = \frac{\koff + \kcat}{\kmp}$$

Conveniently, the ratio of lognormal variables $\frac{X_1}{X_2}$ is also lognormal with $\mu_{1/2} = \mu_1 - \mu_2$ and $ \sigma^2_{1/2} = \sigma^2_1 + \sigma^2_2 - \sigma_{x_1, x_2}$. In order to use that fact, we say the sum of the random variables $\koff + \kcat$ is also log-normally distributed. We compute its mean and variance empirically.

kcat_plus_koff = pd.Series(np.repeat(empirical_kcat.values, len(empirical_koff)) +
                           np.tile(empirical_koff.values, len(empirical_kcat)))

log_kcat_plus_koff_mean = np.log(kcat_plus_koff).mean()
log_kcat_plus_koff_var = np.log(kcat_plus_koff).var()

This permits us to produce empirical distributions for $\kon$ and $\kuncat$,

log_kon_normal = scipy.stats.norm(loc=log_kcat_plus_koff_mean-log_empirical_kms.mean(),
                                  scale=sqrt(log_kcat_plus_koff_var+log_empirical_kms.var()))

log_kuncat_normal = scipy.stats.norm(loc=log_kcat_plus_koff_mean-log_empirical_kmp.mean(),
                                     scale=sqrt(log_kcat_plus_koff_var+log_empirical_kmp.var()))

which, along with our empirical distributions for $\koff$ and $\kcat$, define a prior over the 4 kinetic parameters we wish to infer.

We might ask whether these are correlated lognormals...

...Not enough to include covariances in the prior. We set the prior covariance to be a diagonal matrix:

Now that we have a prior, let's examine where the default parameters introduced in §2.1 land in this distribution. I had claimed they were "typical".

3.1.2. Likelihood

We need to define a likelihood $p(D|\theta)$ which measures the probability of producing the observed data given settings of the kinetic parameters $\theta = \{\kon, \koff, \kcat, \kuncat\}$. Our data $D = \{\mathrm{obs}_{[\mathrm{P}]}(t) \, ; t \in 0...0.5\}$ are an observed trajectory of concentrations of reaction product P. Each setting of the kinetic parameters corresponds to a trajectory of concentrations of P (via a numerical integration). Intuitively, parameter sets which result in trajectories very near the observed trajectory are more likely. Therefore, our likelihood should measure the distance between the observed $\{\mathrm{obs}_{[\mathrm{P}]}(t) \, ; t \in 0...0.5 \}$ and predicted $\{ u_{[\mathrm{P}]}(t, \theta) \, ; t \in 0...0.5\}$.

How far should the predicted trajectory be allowed to stray from the measured $\{\mathrm{obs}_{[\mathrm{P}]}(t) \}$? The likelihood is really our statement about the presumed noise in our measurements. If we believe our measurements to be noiseless, then our likelihood should concentrate tightly around our measurements (a dirac $\delta$ in the limit), and we would only admit kinetic parameters that interpolate the observed $\{\mathrm{obs}_{[\mathrm{P}]}(t) \}$ almost exactly. In reality, no measurement is noiseless, so we propose the following noise model:

Supposing the detection of each molecule of P is an independent binary random variable with error rate $\sigma$ then the aggregate random variable $\mathrm{N}_{[\mathrm{P}]}(t)$ is gaussian-distributed $\sim \mathcal{N}( \mathrm{obs}_{[\mathrm{P}]}(t), \, \sigma \cdot \sqrt{ \mathrm{obs}_{[\mathrm{P}]}(t)} )$. The variance of the gaussian grows as the square root of the mean, via a Central Limit Theorem argument. We can represent this noise model (and consequently, likelihood) visually as:

σ = 5 # arbitrary magic number represents detection noise level

Concretely, the likelihood is the product distribution of each of the gaussian marginals centered around the measurements. These form a multivariate normal, diagonal since we neglect to add covariances.

$$p(D|\theta) = \displaystyle \prod_{t=0}^{0.5} p_t \left(u_{[\mathrm{P}]}(t, \theta)\right) \textrm{ where } p_t \textrm{ is the density of } \mathrm{N}_{[\mathrm{P}]}(t) \sim \mathcal{N} \left( \mathrm{obs}_{[\mathrm{P}]}(t), \, \sigma \cdot \sqrt{ \mathrm{obs}_{[\mathrm{P}]}(t) } \right)$$

Which leaves us with a "hyperparameter" $\sigma$, which we have set arbitrarily above.

likelihood_dist = multivariate_normal(mean=observations.values[1:], cov=σ * np.diag(sqrt(observations.values[1:])))

def likelihood_logpdf(ut): return likelihood_dist.logpdf(ut)

3.1.3. Metropolis-Hastings

We can now evaluate the prior $p(\theta)$ and the likelihood $p(D|\theta)$ of kinetic parameters $\theta = \{\kon, \koff, \kcat, \kuncat\}$. Those two distributions permit us to elaborate an Markov Chain Monte Carlo (MCMC) routine to sample from the posterior $p(\theta|D) \propto p(D|\theta) \cdot p(\theta)$. The algorithm is as follows:

Repeat:

  1. Draw kinetic parameters from the proposal distribution.
  2. Integrate the system with the proposed kinetic parameters.
  3. Evaluate the likelihood of the trajectory generated in step 2.
  4. Accept/Reject the proposal by a Metropolis-Hastings criterion.
  5. Append the current kinetic parameters to the Markov Chain.
  6. Construct a proposal distribution around the current kinetic parameters.

Since the likelihood assigns most of the probability mass to a fairly narrow region of parameter space, most parameter sets have extremely low probability. In order to preserve some numerical stability, we log-transform the typical Metropolis-Hastings expressions. So typically $π_t = \mathrm{likelihood\_pdf}(u_t) \cdot \mathrm{prior\_pdf}(θ_t)$ and the acceptance criterion is $\frac{π_{t+1}}{π_t} > \mathrm{rand}([0,1])$. In log space, the acceptance criterion becomes: $\log(π_{t+1}) - \log(π_t) > \log(\mathrm{rand}([0,1]))$ with $\log(π_t) = \mathrm{likelihood\_logpdf}(u_t) + \mathrm{prior\_logpdf}(θ_t)$.

def MH_MCMC(chain_length=1e3):

    θt = sample_prior()
    ut = simulate_measurements(exp_params(θt))
    πt = likelihood_logpdf(ut) + prior_logpdf(**θt)
    if all(ut == 0): return MH_MCMC(chain_length)

    cov = np.eye(4) * 5e-4
    i = 0
    accept_ratio = 0
    chain = []
    samples = []

    while i < chain_length:

        θtp1 = proposal(θt, cov)
        utp1 = simulated_measurements(θtp1)
        πtp1 = likelihood_logpdf(utp1) + prior_logpdf(**θtp1)

        if πtp1 - πt > np.log(np.random.rand()):

            θt, ut, πt = θtp1, utp1, πtp1
            accept_ratio += 1

        chain.append(θt)
        samples.append(ut)

        i += 1

        if i % 100 == 0 and i > 300:
            # cov = pd.DataFrame(chain[100:]).cov()
            print(i, end='\r')

    chain = pd.DataFrame(chain)
    samples = pd.DataFrame(np.hstack((np.zeros((len(chain), 1)), samples)), columns=observations.index)
    accept_ratio = accept_ratio/chain_length

    return chain, samples, accept_ratio

Our proposal density for the time being can be a simple isotropic gaussian around the current parameters.

def proposal(θt, cov):

    μ = [θt['k_on'], θt['k_off'], θt['k_cat'], θt['k_uncat']]

    θtp1 = dict(zip(['k_on', 'k_off', 'k_cat', 'k_uncat'], np.random.multivariate_normal(μ, cov)))

    return θtp1

Now let's put it into practice:

chain_length = 1e3
chain, samples, accept_ratio = MH_MCMC(chain_length=chain_length)
print('accept_ratio:', accept_ratio)
accept_ratio: 0.151
def fig_style_3(ax):
    for side in ["right","top"]: ax.spines[side].set_visible(False)
    ax.set_xlabel('chain',  weight='bold')
    ax.set_ylabel('log parameter values',  weight='bold')
def plot_chain(chain, ax=None):
    if ax is None: fig, ax = plt.subplots()
    chain.plot.line(xlim=(0,len(chain)), color=[c[param_name] for param_name in chain.columns], ax=ax)

    for param_name in chain.columns:
        param_value = default_kinetic_params[param_name]
        ax.axhline(np.log10(param_value), lw=0.5, color=c[param_name], linestyle='--')
        ax.fill_between(np.arange(len(chain)), chain[param_name], np.repeat(np.log10(param_value), len(chain)), color=c[param_name], alpha=0.05)

    fig_style_3(ax)
plot_chain(chain)
sns.pairplot(chain, kind="kde")
resize_fig(600, 600)
def plot_samples(samples, ax=None):
    if ax is None: fig, ax = plt.subplots()
    observations.plot.line(marker='o', lw=0, color=c['P'], ylim=(-300, 10800), ax=ax, legend=True)
    samples.T.plot.line(colormap=plt.get_cmap('plasma'), alpha=0.1, ax=ax, legend=False, zorder=1)
    fig_style(ax)
plot_samples(samples)
def MCMC_run():
    chain, samples, accept_ratio = MH_MCMC(chain_length=chain_length)
    fig, axs = plt.subplots(1, 2)
    plot_chain(chain, ax=axs[0])
    plot_samples(samples, ax=axs[1])
    print('accept_ratio:', accept_ratio)
MCMC_run()
accept_ratio: 0.079
MCMC_run()
accept_ratio: 0.101
MCMC_run()
accept_ratio: 0.118

A few things pop out from the above chains:

  1. It appears to be possible to closely fit the observed data with very different parameter sets than the ones used to generate the observed trajectory.
  2. It appears that our chain is finding local maxima in the posterior and struggling to escape.
    Note: Some of the above trajectories appear non-smooth. That’s only a consequence of the fact we’re visualizing a coarse sampling of those trajectories -- the underlying trajectories are sampled much more densely by scipy’s integrator.
modified_traj_full = euler_full_modified(dt, steps, **default_kinetic_params, **default_initial_conditions)
ax = modified_traj_full[['S', 'E', 'ES', 'P']].plot.line(title=param_string(**default_initial_conditions, **default_kinetic_params), color=color(default_traj_full.columns))
fig_style(ax)
ax = modified_traj_full.iloc[500:][['k_off_ES', 'k_on_E_S', 'k_cat_ES', 'k_uncat_E_P']].plot.line(color=color(default_traj_full.columns))
None
$$\begin{aligned} \frac{d[\mathrm{S}]}{dt} &= k_{\mathrm{off}}[\mathrm{ES}] - k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] \\ \frac{d[\mathrm{E}]}{dt} &= k_{\mathrm{off}}[\mathrm{ES}] - k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] + k_{\mathrm{cat}}[\mathrm{ES}] - k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ \frac{d[\mathrm{ES}]}{dt} &= - k_{\mathrm{off}}[\mathrm{ES}] + k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] - k_{\mathrm{cat}}[\mathrm{ES}] + k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ \frac{d[\mathrm{P}]}{dt} &= k_{\mathrm{cat}}[\mathrm{ES}] - k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \end{aligned}$$

3.2 Frequentist Approach: Inference by Optimization

In the previous section, we conducted a random walk in parameter space, biasing our random walk towards regions of the parameter space where both the prior probability and likelihood were greater. After a certain number of samples (the "burn in" phase), the samples from our random walk could be said to be drawn from the (exact) posterior distribution over the kinetic parameters.

An alternative approach begins with another premise:

  • Suppose we want to incorporate no prior knowledge, and let the timeseries data alone govern our determination of our enzyme's kinetic parameters.
  • Suppose as well that instead of searching for a distribution of plausible parameters, we're only interested in finding the single most likely set of parameters.

These two choices recast the inference task as an optimization problem. We'll explore two approaches to optimize the kinetic parameters to fit the observed data.

3.2.1 Forward Sensitivities

Optimization problems require an objective, such as minimizing a loss (or cost) function. Let's use the conventional squared error between our trajectory $u$ and the data $d$:
$G(u(t, \theta)) = \sum_t (\| \mathrm{obs}(t) - u(t, \theta) \|_2)^2$ as the loss function we'll minimize (illustrated below).

def loss(u): return np.linalg.norm(observations - u.loc[observations.index, 'P'])**2

In order to optimize our parameters $\theta$ with respect to to our loss function $G$, we need a means to evaluate the gradient of the loss with respect to the parameters. Naïvely:

$$\frac{dG(u(t, \theta))}{d\theta} = \frac{d}{d\theta} \sum_t(\| \mathrm{obs}(t) - u(t, \theta) \|_2)^2 = \sum_t \left[ 2(\mathrm{obs}(t) - u(t, \theta)) \frac{du(t, \theta)}{d\theta} \right]$$

However, the quantity $\frac{du(t, \theta)}{d\theta}$ (called the sensitivity of the solution to a parameter) is not immediately available. We can derive it as follows:

Our original differential equation is $\frac{du(t, \theta)}{dt} = f(u(t, \theta), \theta)$. If we take $\frac{\partial}{\partial\theta} \left[ \frac{du(t, \theta)}{dt} \right] = \frac{\partial}{\partial\theta} \left[ f(u(t, \theta), \theta) \right]$, we can rearrange as $\frac{d}{dt} \left[ \frac{\partial u(t, \theta)}{\partial\theta} \right] = \frac{\partial}{\partial\theta} \left[ f(u(t, \theta), \theta) \right]$ and then integrate over $t$ for

$$\int_{t_0}^T\frac{d}{dt} \left[ \frac{\partial u(t, \theta)}{\partial\theta} \right]dt = \int_{t_0}^T\frac{\partial}{\partial\theta} \left[ f(u(t, \theta), \theta) \right]dt = \int_{t_0}^T \left[ \frac{\partial f}{\partial u} \Big|_{u(t, \theta), \theta} \frac{\partial u}{\partial \theta} \Big|_t + \frac{\partial f}{\partial \theta} \Big|_{u(t, \theta), \theta} \right] dt$$

What we've done is define an ODE whose solution (integral) is that missing quantity, the sensitivity $\frac{du(t, \theta)}{d\theta}$. This ODE is aptly named the forward sensitivity ODE. We can integrate both the original ODE and the sensitivity ODE forwards in time together.

But first, we need to understand the constituent expressions: $\frac{\partial f}{\partial u} \Big|_{u(t, \theta), \theta}$ , $\frac{\partial u}{\partial \theta} \Big|_t$ and $\frac{\partial f}{\partial \theta} \Big|_{u(t, \theta), \theta}$

Recall,

$$\frac{du}{dt} = \frac{d}{dt}\begin{bmatrix}[\mathrm{S}] \\ [\mathrm{E}] \\ [\mathrm{ES}] \\ [\mathrm{P}] \end{bmatrix} = \begin{bmatrix} k_{\mathrm{off}}[\mathrm{ES}] - k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] \\ k_{\mathrm{off}}[\mathrm{ES}] - k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] + k_{\mathrm{cat}}[\mathrm{ES}] - k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ - k_{\mathrm{off}}[\mathrm{ES}] + k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] - k_{\mathrm{cat}}[\mathrm{ES}] + k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ k_{\mathrm{cat}}[\mathrm{ES}] - k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \end{bmatrix} = f(u(t, \theta), \theta)$$

$\frac{\partial f}{\partial u} \Big|_{u(t, \theta), \theta}$ is the derivative of the derivative with respect to the state. Since both the state and its derivative are 4D, this quantity is a 4x4 Jacobian:

$$\frac{df}{du} = \begin{bmatrix}\frac{df}{[\mathrm{S}]} & \frac{df}{[\mathrm{E}]} & \frac{df}{[\mathrm{ES}]} & \frac{df}{[\mathrm{P}]} \end{bmatrix} = \begin{bmatrix} -k_{\mathrm{on}}[\mathrm{E}] & -k_{\mathrm{on}}[\mathrm{S}] & k_{\mathrm{off}} & 0 \\ -k_{\mathrm{on}}[\mathrm{E}] & -k_{\mathrm{on}}[\mathrm{S}] - k_{\mathrm{uncat}}[\mathrm{P}] & k_{\mathrm{off}} + k_{\mathrm{cat}} & -k_{\mathrm{uncat}} \\ k_{\mathrm{on}}[\mathrm{E}] & k_{\mathrm{on}}[\mathrm{S}] + k_{\mathrm{uncat}}[\mathrm{P}] & -k_{\mathrm{off}} - k_{\mathrm{cat}} & k_{\mathrm{uncat}} \\ 0 & -k_{\mathrm{uncat}}[\mathrm{P}] & k_{\mathrm{cat}} & -k_{\mathrm{uncat}} \end{bmatrix}$$

$\frac{\partial f}{\partial \theta} \Big|_{u(t, \theta), \theta}$ is the derivative of the derivative with respect to one of the parameters.

$$\frac{\partial f}{\partial k_{\mathrm{on}}} = \begin{bmatrix} -[\mathrm{E}][\mathrm{S}] \\ -[\mathrm{E}][\mathrm{S}] \\ [\mathrm{E}][\mathrm{S}] \\ 0 \end{bmatrix}, \qquad \frac{\partial f}{\partial k_{\mathrm{off}}} = \begin{bmatrix} [\mathrm{ES}] \\ [\mathrm{ES}] \\ -[\mathrm{ES}] \\ 0 \end{bmatrix}, \qquad \frac{\partial f}{\partial k_{\mathrm{cat}}} = \begin{bmatrix} 0 \\ [\mathrm{ES}] \\ -[\mathrm{ES}] \\ [\mathrm{ES}] \end{bmatrix}, \qquad \frac{\partial f}{\partial k_{\mathrm{uncat}}} = \begin{bmatrix} 0 \\ -[\mathrm{E}][\mathrm{P}] \\ [\mathrm{E}][\mathrm{P}] \\ -[\mathrm{E}][\mathrm{P}] \end{bmatrix}, \qquad $$

$\frac{\partial u}{\partial \theta} \Big|_t$ is the variable of integration, which means we only need to define a boundary condition for it, in this case, an initial value:

$$ \frac{\partial u}{\partial \theta} \Big|_{t_0} = \frac{\partial}{\partial \theta} u(0, \theta) $$

But since in our case $u(0, \theta) = u(0) = 0$ does not depend on $\theta$, $\frac{\partial u}{\partial \theta} \Big|_{t_0} = 0$.

Now we're ready to augment our original Euler method to compute both $\int_{t_0}^T\frac{du(t, \theta)}{dt} dt$ as before and add $\int_{t_0}^T\frac{\partial}{\partial\theta} \left[ f(u(t, \theta), \theta) \right] dt$.

start = time.process_time()
traj_euler_full_sensitivities = integrate_euler_full_sensitivities(default_kinetic_params)
euler_time = time.process_time() - start

ODE_columns = traj_euler_full_sensitivities.columns[:4]
sensitivity_columns = traj_euler_full_sensitivities.columns[4:]
P_sensitivity_columns = traj_euler_full_sensitivities.columns[7::4]

fig, axs = plt.subplots(1, 2)
traj_euler_full_sensitivities[ODE_columns].plot.line(ax=axs[0], color=color(ODE_columns))
traj_euler_full_sensitivities[sensitivity_columns].plot.line(ax=axs[1])

fig_style(axs[0])
fig_style(axs[1])
# axs[1].hide_xlabel()

Unfortunately, as before, our simple-minded python code, although conceptually helpful, is too slow to use repeatedly inside a loop. Let's once again re-structure this code for scipy.

'our naïve code takes 22.39s, whereas the optimized scipy code takes 0.4221s to generate the same trajectory.'

Recall, computing the sensitivity of the solution with respect to the parameters $\frac{du(t, \theta)}{d\theta}$ was in service of computing the gradient of our loss function with respect to the parameters:

$$\frac{dG(u(t, \theta))}{d\theta} = \sum_t \left[ 2(\mathrm{obs}(t) - u(t, \theta)) \frac{du(t, \theta)}{d\theta} \right]$$

Now, since we set up this problem such that we only observe $\mathrm{obs}_{[\mathrm{P}]}(t)$, we are only able to compare the integrated kinetics of $ u_{[\mathrm{P}]}(t, \theta)$ and so our gradient expression becomes:

$$\frac{dG(u(t, \theta))}{d\theta} = \sum_t \left[ 2(\mathrm{obs}_{[\mathrm{P}]}(t) - u_{[\mathrm{P}]}(t, \theta) ) \right]\frac{ d u_{[\mathrm{P}]}(t, \theta)}{d\theta} $$

Now it's worth lookign specifically at $\frac{ d u_{[\mathrm{P}]}(t, \theta)}{d\theta}$:

traj_scipy_sensitivities[P_sensitivity_columns].plot.line()
<AxesSubplot:>

We notice right away the scale of some of these sensitivities reaches $O(10^6)$. That may be because the parameters span many orders of magnitude, so the sentivities of the system to small perturbations in some parameters may be much greater than others.

We've set ourselves the task of optimizing the 4 parameters in the Michaelis-Menten/Briggs-Haldane kinetics ODE to minimize the squared error with respect to an observed timeseries. In order to intialize this optimization routine, we need somewhere to start from. Let's use the means of the prior distributions (from §3.1.1) for each parameter as a starting point.

θ_0 = {'k_on': exp(log_kon_normal.mean()),
       'k_off': exp(log_koff_normal.mean()),
       'k_cat': exp(log_kcat_normal.mean()),
       'k_uncat': exp(log_kuncat_normal.mean())}

Our gradient descent routine iterates a loop:

  1. Integrate the system ODE and sensitivity ODE with the current parameters.
  2. Compute the gradient of the loss with the current parameters.
  3. Update the parameters with a gradient step
Optimization_Record = namedtuple('Optimization_Record', ['θ', 'u', 'loss', 'G_θ'])

def optimize_by_gradient_descent(θ_0):

    θ_record = []
    u_record = []
    loss_record = []
    grad_record = []
    θ_t = dict(θ_0)
    α = 1
    prev_loss = np.inf

    print(θ_t)

    while α >= 1e-9:

        u = integrate_scipy_full_sensitivities(θ_t)
        G_θ = gradient_of_loss(u)

        curr_loss = loss(u)
        if curr_loss > prev_loss:
            α = α/np.sqrt(10)
            θ_t = θ_record[-1]
            continue

        θ_record.append(θ_t)
        u_record.append(u)
        loss_record.append(curr_loss)
        grad_record.append(G_θ)

        θ_t = {k: max(θ_t[k] + (α * G_θ[k]), 0) for k in θ_t.keys()}
        prev_loss = curr_loss
        print('\t', θ_t, end='\t\t\t\r')

    θ_record = pd.DataFrame(θ_record)
    loss_record = pd.Series(loss_record)
    grad_record = pd.DataFrame(grad_record)
    print('\t', θ_t, end='\t\t\t\n')

    return Optimization_Record(θ=θ_record, u=u_record, loss=loss_record, G_θ=grad_record)
optimization_record = optimize_by_gradient_descent(θ_0)
{'k_on': 1.0489415890738956, 'k_off': 9.301874926576737, 'k_cat': 26.789395694394962, 'k_uncat': 0.8975846605968467}
	 {'k_on': 1.70042263313856, 'k_off': 9.268106147314615, 'k_cat': 26.849749195060024, 'k_uncat': 0.1420784900535258}						
draws = prior_samples(10)
best, optimization_records = optimize_parametersets([exp_params(draw) for draw in draws])
{'k_on': 3.674269568145476, 'k_off': 50.75828616093256, 'k_cat': 1457.665574387546, 'k_uncat': 1.6995029057083366}
	 {'k_on': 3.674269568145476, 'k_off': 50.75828616093256, 'k_cat': 1457.665574387546, 'k_uncat': 1.6995029057083366}						
{'k_on': 0.27763425483875104, 'k_off': 208.4591932293213, 'k_cat': 11.586304702034402, 'k_uncat': 0.024444884645991947}
	 {'k_on': 2.625390436915578, 'k_off': 208.44417026872833, 'k_cat': 20.576895237783855, 'k_uncat': 0}					
{'k_on': 0.00728132784637768, 'k_off': 8316.426718373255, 'k_cat': 9.223678814476987, 'k_uncat': 24.478446695102594}
	 {'k_on': 25.112423355827502, 'k_off': 8316.389850551226, 'k_cat': 26.67355712070862, 'k_uncat': 0}				54302942815254}			
{'k_on': 0.2679359758705066, 'k_off': 0.623710789771037, 'k_cat': 80.7124553599963, 'k_uncat': 4.448920909717443}
	 {'k_on': 1.2719144668684343, 'k_off': 0.5966265004090603, 'k_cat': 80.7167008970781, 'k_uncat': 4.388541693476215}					
{'k_on': 0.8617432905781651, 'k_off': 61.15680743531349, 'k_cat': 159.6574528141114, 'k_uncat': 0.20092963435975683}
	 {'k_on': 0.8617432905781651, 'k_off': 61.15680743531349, 'k_cat': 159.6574528141114, 'k_uncat': 0.20092963435975683}					
{'k_on': 0.6712134246854804, 'k_off': 0.8961945331793285, 'k_cat': 174.82025457526467, 'k_uncat': 0.18624597457495648}
	 {'k_on': 0.6712134246854804, 'k_off': 0.8961945331793285, 'k_cat': 174.82025457526467, 'k_uncat': 0.18624597457495648}			
{'k_on': 0.17921434549351445, 'k_off': 126.01795603426227, 'k_cat': 27.082066610667063, 'k_uncat': 65.99528266031089}
	 {'k_on': 64.36344159611156, 'k_off': 108.7821457909459, 'k_cat': 71.28177305879433, 'k_uncat': 16.976661850091762}						
{'k_on': 0.052732959517730535, 'k_off': 0.7301498270593921, 'k_cat': 3318.4310896917086, 'k_uncat': 12.631881055409037}
	 {'k_on': 0.06373284451700806, 'k_off': 0.730119208534845, 'k_cat': 3318.431089845633, 'k_uncat': 12.631841202398144}					
{'k_on': 0.037759929535704145, 'k_off': 12.313845514207461, 'k_cat': 471.0186587235138, 'k_uncat': 12.939553968850886}
	 {'k_on': 1.0380684896840706, 'k_off': 12.311482000790747, 'k_cat': 471.0187354271704, 'k_uncat': 12.936795364466498}				
{'k_on': 59.54270359901848, 'k_off': 5212.013975481148, 'k_cat': 634.0893134249667, 'k_uncat': 24.537061927393133}
	 {'k_on': 64.38357258593143, 'k_off': 5211.956550061441, 'k_cat': 634.5624070915211, 'k_uncat': 4.577554916752057}					
default_kinetic_params
{'k_on': 1,
 'k_off': 500,
 'k_cat': 30,
 'k_uncat': 0.01,
 'k_ms': 530.0,
 'k_mp': 53000.0}
pd.DataFrame([optimization_record.loss for optimization_record in optimization_records]).T.add_prefix('prior draw ').plot.line(logy=True, title='Loss trajectories for 10 draws from the prior')
<AxesSubplot:title={'center':'Loss trajectories for 10 draws from the prior'}>
plot_optimization_trajectories(optimization_records)
plt.tight_layout()
plt.rcParams['figure.figsize'] = [12, 5]

This doesn't appear to work so well, so let's try once more to optimize in log space. Our Jacobian doesn't change, but the $\frac{\partial f}{\partial \theta} \Big|_{u(t, \theta), \theta}$ terms change to $\frac{\partial f}{\partial \log(\theta)} \Big|_{u(t, \theta), \theta}$ terms:

$$\frac{\partial f}{\partial \log(k_{\mathrm{on}})} = \begin{bmatrix} -k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] \\ -k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] \\ k_{\mathrm{on}}[\mathrm{E}][\mathrm{S}] \\ 0 \end{bmatrix}, \qquad \frac{\partial f}{\partial \log(k_{\mathrm{off}})} = \begin{bmatrix} k_{\mathrm{off}}[\mathrm{ES}] \\ k_{\mathrm{off}}[\mathrm{ES}] \\ -k_{\mathrm{off}}[\mathrm{ES}] \\ 0 \end{bmatrix}, \qquad \frac{\partial f}{\partial \log(k_{\mathrm{cat}})} = \begin{bmatrix} 0 \\ k_{\mathrm{cat}}[\mathrm{ES}] \\ -k_{\mathrm{cat}}[\mathrm{ES}] \\ k_{\mathrm{cat}}[\mathrm{ES}] \end{bmatrix}, \qquad \frac{\partial f}{\partial \log(k_{\mathrm{uncat}})} = \begin{bmatrix} 0 \\ -k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \\ -k_{\mathrm{uncat}}[\mathrm{E}][\mathrm{P}] \end{bmatrix}, \qquad $$

We'll skip straight to the scipy implementation.

traj_scipy_log_sensitivities = integrate_scipy_log_sensitivities(default_kinetic_params)

fig, axs = plt.subplots(1, 2)
traj_scipy_log_sensitivities[ODE_columns].plot.line(ax=axs[0], color=color(ODE_columns))
traj_scipy_log_sensitivities[sensitivity_columns].plot.line(ax=axs[1])

fig_style(axs[0])
fig_style(axs[1])

Our gradient evaluation changes...

def optimize_log_parameters_by_gradient_descent(log_θ_0):
    '''Note: this function expects parameters to be in log space'''
    log_θ_record = []
    u_record = []
    loss_record = []
    grad_record = []
    log_θ_t = dict(log_θ_0)
    α = 1
    prev_loss = np.inf

    print(exp_params(log_θ_t))

    while α >= 1e-9:

        u = integrate_scipy_log_sensitivities(exp_params(log_θ_t))
        G_θ = gradient_of_loss(u)

        curr_loss = loss(u)
        if curr_loss > prev_loss:
            α = α/np.sqrt(10)
            log_θ_t = log_θ_record[-1]
            continue

        log_θ_record.append(log_θ_t)
        u_record.append(u)
        loss_record.append(curr_loss)
        grad_record.append(G_θ)

        log_θ_t = {k: max(log_θ_t[k] + (α * G_θ[k]), 0) for k in log_θ_t.keys()}
        prev_loss = curr_loss
        print('\t', exp_params(log_θ_t), end='\t\t\t\r')

    log_θ_record = pd.DataFrame(log_θ_record)
    loss_record = pd.Series(loss_record)
    grad_record = pd.DataFrame(grad_record)
    print('\t', exp_params(log_θ_t), end='\t\t\t\r')

    return Optimization_Record(θ=log_θ_record, u=u_record, loss=loss_record, G_θ=grad_record)
log_θ_0 = {'k_on': log_kon_normal.mean(),
           'k_off': log_koff_normal.mean(),
           'k_cat': log_kcat_normal.mean(),
           'k_uncat': log_kuncat_normal.mean()}
optimization_record = optimize_log_parameters_by_gradient_descent(log_θ_0)
{'k_on': 1.0489415890739007, 'k_off': 9.301874926576735, 'k_cat': 26.789395694394965, 'k_uncat': 0.8975846605968499}
	 {'k_on': 3.636910445279411, 'k_off': 8.005958601938623, 'k_cat': 32.10917110833029, 'k_uncat': 1.0}				
def optimize_log_parametersets(log_parametersets):

    current_best_loss = np.inf
    optimization_records = []

    for i, log_θ_0 in enumerate(log_parametersets):

        record = optimize_log_parameters_by_gradient_descent(log_θ_0)
        optimization_records.append(record)
        if record.loss.iloc[-1] < current_best_loss:
            current_best_loss = i

    return current_best_loss, optimization_records
draws = prior_samples(10)
best, optimization_records = optimize_parametersets([exp_params(draw) for draw in draws])
{'k_on': 2.51062821626494, 'k_off': 1.672868963540867, 'k_cat': 56.33479407689398, 'k_uncat': 25.07298320708997}
	 {'k_on': 10.791426759436343, 'k_off': 0, 'k_cat': 57.67324108528216, 'k_uncat': 22.934724678644514}				070869832}					
{'k_on': 0.5382034283710937, 'k_off': 5.948477437137724, 'k_cat': 96.30612342763925, 'k_uncat': 66.47415218026515}
	 {'k_on': 13.617914581407854, 'k_off': 0, 'k_cat': 97.37670850070248, 'k_uncat': 65.1519953075734}				4601684154674}			
{'k_on': 1.5750109226783715, 'k_off': 21.78930047787638, 'k_cat': 3.8243584953980605, 'k_uncat': 3.7377578341647406}
	 {'k_on': 4.576175456236011, 'k_off': 21.44916668707143, 'k_cat': 20.135442693156513, 'k_uncat': 0}					9927913839771}			
{'k_on': 2.4098284564304358, 'k_off': 139.6478555754508, 'k_cat': 98.91259200374849, 'k_uncat': 0.15989517946525372}
	 {'k_on': 2.4098284564304358, 'k_off': 139.6478555754508, 'k_cat': 98.91259200374849, 'k_uncat': 0.15989517946525372}				
{'k_on': 0.00023321521059935536, 'k_off': 2.9302197422920044, 'k_cat': 0.05832050505705417, 'k_uncat': 31.716924040486543}
	 {'k_on': 25.191662693748345, 'k_off': 0, 'k_cat': 35.30336155385477, 'k_uncat': 19.6400488747992}						19252328482}					
{'k_on': 1.69136162851864, 'k_off': 6.355268420368663, 'k_cat': 0.30141446188913174, 'k_uncat': 9.892202023861197}
	 {'k_on': 10.411303220158953, 'k_off': 1.5646535928592409, 'k_cat': 20.55771178840932, 'k_uncat': 0.4852097926388428}					
{'k_on': 6.109624950296204, 'k_off': 2.1367300505068565, 'k_cat': 141.3512194969451, 'k_uncat': 98.19264658567204}
	 {'k_on': 12.38477756301105, 'k_off': 0, 'k_cat': 141.8048563860059, 'k_uncat': 97.62381778009816}					3237192505}					
{'k_on': 25.859944310749142, 'k_off': 42.735518282387496, 'k_cat': 0.027813342417402825, 'k_uncat': 0.0009482336979780397}
	 {'k_on': 25.86314365092915, 'k_off': 42.734102360879405, 'k_cat': 20.066014564774253, 'k_uncat': 0}				
{'k_on': 0.2416186550388689, 'k_off': 0.2386330734397468, 'k_cat': 3.3642253634090515, 'k_uncat': 568.927904184962}
	 {'k_on': 97.34882379704321, 'k_off': 0, 'k_cat': 103.66876459309285, 'k_uncat': 560.5482216295655}				
{'k_on': 0.5105218699587306, 'k_off': 0.47280244608099287, 'k_cat': 0.42158026464061854, 'k_uncat': 7.312360869761177}
	 {'k_on': 7.745952117006329, 'k_off': 0, 'k_cat': 20.06337490235761, 'k_uncat': 0}					150303415378}			4663468171374}			
pd.DataFrame([optimization_record.loss for optimization_record in optimization_records]).T.add_prefix('prior draw ').plot.line(logy=True, title='Loss trajectories for 10 draws from the prior')
<AxesSubplot:title={'center':'Loss trajectories for 10 draws from the prior'}>
plot_optimization_trajectories(optimization_records)
plt.tight_layout()
plt.rcParams['figure.figsize'] = [12, 5]

3.2.2. Adjoint Method

How is Adjoint better? how does it scale differently with parameters?

$$ $$
# 1. solve forwards: euler_full
# 2. solve adjoint DE
# 3. evaluate integral
adjoint_euler_full(dt, steps, u=, data=default_traj_full.values, *kinetic_params)
def integrate(kinetic_params, dt=dt, initial_conditions=default_initial_conditions):

    [(_, E_0), (_, S_0)] = initial_conditions.items()
    t_eval = observations.index[1:]
    t_span = (0, t_eval[-1])
    y0 = [S_0, E_0, 0, 0]
    kinetic_params = {name: 10**val for name, val in kinetic_params.items()}
    fun = lambda t,y: dy_full(t, y, E_0=E_0, S_0=S_0, **kinetic_params)

    try:
        sol = solve_ivp(fun, t_span, y0, t_eval=t_eval, first_step=dt, max_step=1e-2, method='LSODA')
        return sol.y[3] # Product
    except:
        return np.zeros(10)

4. Conclusions

Michaelis menten isn't even right, that's why the databases are such a mess. You need the right scheme, and the right equations

5. References

  • Thermodynamics of Glycolysis/III%3A_Reactivity_in_Organic_Biological_and_Inorganic_Chemistry_1/08%3A_Mechanisms_of_Glycolysis/8.08%3A_Thermodynamics_of_Glycolysis)